package com.iteima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.UpdateById;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iteima.reggie.common.R;
import com.iteima.reggie.dto.DishDto;
import com.iteima.reggie.entity.Category;
import com.iteima.reggie.entity.Dish;
import com.iteima.reggie.entity.DishFlavor;
import com.iteima.reggie.entity.SetmealDish;
import com.iteima.reggie.mapper.DishMapper;
import com.iteima.reggie.service.CategoryService;
import com.iteima.reggie.service.DishFlavorService;
import com.iteima.reggie.service.DishService;
import com.iteima.reggie.service.SetmealDishService;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 分页查询菜品信息
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name ){
        log.info("page={},pageSize={},name={}",page,pageSize,name);
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件(注意当name不为空才添加like条件)
        dishLambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //添加排序条件
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo,dishLambdaQueryWrapper);

        List<Dish> records = pageInfo.getRecords();

        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");


        List<DishDto> list  = records.stream().map(item ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //判断分类不为空,再赋值
           if(category != null){
               String categoryName = category.getName();
               dishDto.setCategoryName(categoryName);

           }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
    log.info(dishDto.toString());
    dishService.saveWithFlavor(dishDto);
    return R.success("新增菜品成功");
    }

    /**
     * 根据菜品id获取dishDto
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor( dishDto);
        return R.success("修改成功");
    }

    /**
     * 根据分类id查询菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        log.info("category:{}",dish);

        Long categoryId = dish.getCategoryId();
        LambdaQueryWrapper<Dish>queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,categoryId);
        queryWrapper.eq(Dish::getStatus,1);//查询状态为1(起售)的菜品
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);//排序条件
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map(item ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId1 = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if ( category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(lambdaQueryWrapper);

            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());



        return  R.success(dishDtoList);
    }

    /**
     * 批量or删除
     * @param list
     * @return
     */
    @DeleteMapping
    public R<String> deleteList(@RequestParam("ids") List<Long> list){
        log.info("id={}",list);

        if (list == null){
            return R.error("没有选中菜品");

        }
        //判断套餐中是否包含该菜品
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getDishId,list);
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
        if (!setmealDishes.isEmpty()){
            return R.error("所选菜品绑定了套餐,不能删除!");
        }
        dishMapper.deleteBatchIds(list);
        return R.success("删除成功");
    }
    @PostMapping("/status/{status}")
    public R<String> upStatus( @RequestParam List<Long> ids,@PathVariable Integer status){
    log.info("id={},ids={}",status,ids);
    dishService.upStatusWithIds(ids,status);
    return R.success("修改成功!");

    }
}
